﻿using Sidvall.WorkItemManager.Data.Entity.Entities;
using System.Linq;
using System.Threading.Tasks;

namespace Sidvall.WorkItemManager.Data.Entity.Model.StorageManagers
{
    public static partial class WorkerManager
    {
        static partial void OnExecute(StorageManager storageManager, Sidvall.Business.DataPortalContext<Sidvall.Data.CommandCriteria, Sidvall.Data.CommandCriteria> dataPortalContext)
        {
            dataPortalContext.Tasks.Add(OnExecuteTask(storageManager, dataPortalContext));
        }
        private static async Task OnExecuteTask(StorageManager storageManager, Sidvall.Business.DataPortalContext<Sidvall.Data.CommandCriteria, Sidvall.Data.CommandCriteria> dataPortalContext)
        {
            bool result;

            switch (dataPortalContext.OperationContext.CriteriaId)
            {
                case ParameterManager.WorkerResetParameterName:
                    result = await WorkerResetAsync(storageManager,
                        dataPortalContext.OperationContext.Parameters.ValueToEnumerableInt64("WorkerIds"),
                        dataPortalContext.OperationContext.Parameters.ValueToNullableBoolean("IsEnabled")).ConfigureAwait(false);
                    if (result)
                        dataPortalContext.Result = Sidvall.Business.DataPortalResult.Ok;
                    else
                        dataPortalContext.Result = Sidvall.Business.DataPortalResult.Skipped;
                    break;
                default:
                    break;
            }
        }

        #region WorkItemUpdateAsync

        public static async Task<bool> WorkerResetAsync(StorageManager storageManager, System.Collections.Generic.IEnumerable<long> workerIds, bool? isEnabled)
        {
            System.Linq.IQueryable<Worker> query;

            query = (from o in storageManager.ObjectContext.Worker
                     where workerIds.Contains(o.WorkerId)
                     select o);
            var items = await Sidvall.WorkItemManager.Data.Entity.SystemContext.Current.DataManager.GetEntityObjectsAsync(query).ConfigureAwait(false);
            if (!items.Any())
                return false;
            foreach (var item in items)
            {
                if (isEnabled != null)
                    item.IsEnabled = isEnabled.Value;
            }
            await Sidvall.WorkItemManager.Data.Entity.SystemContext.Current.DataManager.SaveChangesAsync(storageManager.ObjectContext).ConfigureAwait(false);
            return true;
        }

        #endregion
    }
}